import isMobile from "is-mobile"
import { ReactNode, useEffect, useState } from "react"
import "./index.less"

export interface ToastProps {
    title: string
    content: string | ReactNode
    showToast: boolean
    onCancel?: () => void
    onConfirm?: () => void
}

export default function Toast(props: ToastProps) {
    const { title, content, onCancel, onConfirm, showToast } = props

    const [display, setDisplay] = useState<"none" | "block">(showToast ? "block" : "none")

    useEffect(() => {
        setDisplay(showToast ? "block" : "none")
    }, [showToast])

    const im = isMobile()
    const getClassName = (name: string) => (im ? `${name} m-${name}` : name)

    return (
        <div className="toast-wrapper" style={{ display }}>
            <div className="toast-bg" onClick={onCancel || (() => setDisplay("none"))}></div>
            <div className={getClassName("toast")}>
                <div className={getClassName("toast-title")}>{title}</div>
                <div className={getClassName("toast-content")}>{content}</div>
                <div className={getClassName("toast-button")}>
                    <button className={getClassName("toast-cancel")} onClick={onCancel || (() => setDisplay("none"))}>
                        取消
                    </button>
                    <button className={getClassName("toast-confirm")} onClick={onConfirm}>
                        前往
                    </button>
                </div>
            </div>
        </div>
    )
}
